<?php
require $_SERVER['DOCUMENT_ROOT'].'/../_core/common.php';

$msg = array();

//权限验证
if( Role::init() == false ){
	$msg['error'] = false;
	$msg['string'] = '权限不足！';
	$myjson = json_encode($msg); 
	echo $myjson; 
	exit;
}

$db = new DB('news');

$old_category_id = isset($_POST['old_category_id']) ? intval($_POST['old_category_id']) : 0;
$new_category_id = isset($_POST['new_category_id']) ? intval($_POST['new_category_id']) : 0;
$title_id = isset($_POST['title_id']) ? h($_POST['title_id']) : '';
$title_id_arr = explode('|',$title_id);

if(empty($title_id) || $old_category_id==0 || $new_category_id==0){
	$msg['error'] = false;
	$msg['string'] = '参数有误！';
}else{
	$title_count = 0;
	$title_id_string = '';
	
	foreach($title_id_arr as $key=>$val){
		if($val != ''){
			//更新category_id,updated字段
			$data = array('category_id'=>$new_category_id,'updated'=>time());
			$db->table('news')->where('title_id="'.$val.'"')->update($data)->run();
			
			//更新counts字段
			//旧的-1
			$old_category_sql = 'select counts from categories where id='.$old_category_id;
			$old_category_rs = $db->query($old_category_sql)->getOne();
			$old_data=array('counts'=>($old_category_rs['counts']-1));
			$db->table('categories')->where('id='.$old_category_id)->update($old_data)->run();
			//新的+1
			$new_category_sql = 'select counts,title from categories where id='.$new_category_id;
			$new_category_rs = $db->query($new_category_sql)->getOne();
			$new_data=array('counts'=>($new_category_rs['counts']+1));
			$db->table('categories')->where('id='.$new_category_id)->update($new_data)->run();
			
			$title_count++;
			$title_id_string .= $val.',';
		}
	}
	
	$title_id_string = substr($title_id_string, 0, -1);
	
	//记录动作日志
	Log::logs_articles($new_category_id, 9, $title_id_string);

	$msg['error'] = true;
	$msg['string'] = '批量移动 '.$title_count.' 篇新闻成功!';
}

$myjson = json_encode($msg); 
echo $myjson; 
exit;